import json

import requests

from utils.log_util import logger
from utils.read import base_data

api_root_url = base_data.read_ini()['host']['api_sit_url']

class RestClient:
    def __init__(self):
        self.api_root_url = api_root_url
        self.session = requests.Session()#headers会赋值给self.session————requests.Session().get之类的才能保存传递session，cookie

    def get(self,url,**kwargs):
        #return requests.get(self.api_root_url + url,**kwargs) #**kwargs可传入任意规定好的关键字参数，如这里requests.get()里的params=XXXX这种样式
        return self.request(url,'GET',**kwargs)#self.request(url,method,**kwargs):因为用的类里下面自定义的函数request，所以是self.的形式

    def post(self,url,**kwargs):
        #return requests.post(self.api_root_url + url,**kwargs)
        return self.request(url, 'POST', **kwargs)

    def put(self,url,**kwargs):
        return self.request(url,'PUT',**kwargs)

    def dlete(self,url,**kwargs):
        return self.request(url, 'DELETE', **kwargs)

    def request(self,url,method,**kwargs):
        self.request_log(url, method, **kwargs)
        if method == 'GET':
            return self.session.get(self.api_root_url + url, **kwargs)
        if method == 'POST':
            return self.session.post(self.api_root_url + url, **kwargs)
        if method == 'PUT':
            return self.session.put(self.api_root_url + url, **kwargs)
        if method == 'DELETE':
            return self.session.delete(self.api_root_url + url, **kwargs)

    def request_log(self,url,method,**kwargs):
        json_data = dict(**kwargs).get('json')
        params = dict(**kwargs).get('params')
        data = dict(**kwargs).get('data')
        headers = dict(**kwargs).get('headers')
        logger.info("接口请求地址>>>{}".format(self.api_root_url + url))
        logger.info("接口请求的方法>>>{}".format(method))
        if json_data is not None:
            logger.info("接口请求的json参数>>>\n{}".format(json.dumps(json_data, ensure_ascii=False, indent=2)))  # ensure_ascii=False:取消默认ascii编码，indent=2,缩进=2格
        if params is not None:
            logger.info("接口请求的params参数>>>\n{}".format(json.dumps(params, ensure_ascii=False, indent=2)))
        if data is not None:
            logger.info("接口请求的data参数>>>\n{}".format(json.dumps(data, ensure_ascii=False, indent=2)))
        if headers is not None:
            logger.info("接口请求的headers参数>>>\n{}".format(json.dumps(headers, ensure_ascii=False, indent=2)))

